﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Domain;
using EmailMarketingDao;
using Tool;

namespace EmailMarketingDomain
{
    public abstract class ProxyPostOffice
    {
        public int FinishedTaskCount { get; set; }//累计已完成任务数
        public int SuccessFinishedTaskCount { get; set; }//累计已成功完成任务数
        public static int WorkSpeed { get; set; }//工作速度
        protected Mail Mailconfig { get; set; }


        /// <summary>
        ///  开始工作
        /// </summary>
        public void StartToWork()
        {
            while (true)
            {
                Letter letter = null;
                try
                {
                    Thread.Sleep(WorkSpeed);
                    var smtp = SmtpServerDao.GetEmailSmtpServcerBySmtp(Mailconfig.SmtpServer.Host);
                    if (smtp.HasSendCount < smtp.DefaultDayMaxSend)
                    {
                        var acount = SendEmailAcountDao.GetAvailableSendAcountBySMTP(Mailconfig.SmtpServer.Host);
                        if (acount != null)
                        {
                            Mailconfig.SmtpServer.Credentials = new NetworkCredential(acount.Acount, acount.Password);
                            letter = NativePostOffice.GetLetter();
                            if (letter != null)
                            {
                                //letter.ToSendAddress = "827756467@qq.com";
                                var ret = Mailconfig.SendMail(letter.ToSendAddress, letter.Title, letter.Content, acount.Acount, null);
                                if (ret)
                                {
                                    SendEmailAcountDao.UpdateSendAcountHasendCount(acount.Acount,
                                        acount.HasSendCount + 1);
                                    SmtpServerDao.UpdateSMTPHasendCount(Mailconfig.SmtpServer.Host,
                                        smtp.HasSendCount + 1);
                                    NativePostOffice.ALLSuccessFinishedTaskCount += 1;
                                    SuccessFinishedTaskCount += 1;
                                }
                                else
                                    throw new Exception("邮件发送后，返回错误结果！邮局：" + Mailconfig.SmtpServer.Host);
                                NativePostOffice.AllFinishedTaskCount += 1;
                                FinishedTaskCount += 1;
                                continue;
                            }
                        }
                    }
                    //休息10秒
                    Thread.Sleep(10000);

                }
                catch (Exception ex)
                {
                    NativePostOffice.AddLetter(letter);
                    CustomsLog.WriteExceptionErrorLog("QQ邮局工作出错", ex);
                }
            }
        }

    }
}
